//
//  MyMoneyViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/9/30.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "MyMoneyViewController.h"
#import "MyMoneyFirstCell.h"
#import "MyMoneyBottomCell.h"
#import "RecordListModel.h"
#import "MyMoneyRuleViewController.h"
@interface MyMoneyViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationBarDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *listDataArray;
@end

@implementation MyMoneyViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"吉吉积分";
    [self createTabelveiew];
    [self getRecoredList];
//    self.navigationController.navigationBar.subviews.firstObject.alpha = 0;

    
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated{
    [self createNavagationBackBtn];
    CGFloat offset = self.tableView.contentOffset.y;
    [self.navigationController.navigationBar
     setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:201/255.0 blue:31/255.0 alpha:(offset / 64)>0.99?0.99:(offset / 64)]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar
     setShadowImage:[UIImage new]];
//            [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; //去除 navigationBar 底部的细线
//            self.navigationController.navigationBar.shadowImage = [UIImage new];
//     self.navigationController.navigationBar.translucent = NO;
//    self.navigationController.navigationBar.subviews.firstObject.alpha = 0.0f;
    self.tabBarController.tabBar.hidden = YES;
}

-(UIImage*) imageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    self.tabBarController.tabBar.hidden = NO;
}
-(void)createNavagationBackBtn{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 6 , 67, 23);
    UIImageView *backImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigator_btn_back"]];
    backImg.frame = CGRectMake(-10, 10, 22, 22);
    [backBtn addSubview:backImg];
    [backImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backBtn.mas_left).offset(-10);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(22, 22));
    }];
    UILabel *backText = [[UILabel alloc] initWithFrame:CGRectMake(12, 10, 65, 22)];
//    backText.text = @"返回";
    backText.font = [UIFont systemFontOfSize:17];
    [backText setBackgroundColor:[UIColor clearColor]];
    [backText setTextColor:[UIColor whiteColor]];
    [backBtn addSubview:backText];
    [backText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backImg.mas_right).offset(2);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(65, 22));
    }];
    [backBtn addTarget:self action:@selector(leftBarButtonItemPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    [self.navigationItem setLeftBarButtonItem:leftButton];
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 80, 44);
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    [rightBtn setTitle:@"详细规则" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(goRulePage:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpace.width = -20;
    self.navigationItem.rightBarButtonItem = rightBar;
  self.navigationController.navigationBar.subviews.firstObject.alpha = 0.0f;
}

-(void)goRulePage:(UIButton *)btn{
    MyMoneyRuleViewController *ruleVc = [[MyMoneyRuleViewController alloc] init];
    [self.navigationController pushViewController:ruleVc animated:YES];
}
-(void)leftBarButtonItemPressed:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)createTabelveiew{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[MyMoneyFirstCell class] forCellReuseIdentifier:@"MyMoneyFirstCell"];
    [self.tableView registerClass:[MyMoneyBottomCell class] forCellReuseIdentifier:@"MyMoneyBottomCell"];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }

}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return self.listDataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        MyMoneyFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyMoneyFirstCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.gosignBlock = ^{
            [self goSign];
        };
        cell.closeViewBlock = ^{
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];

        };
        return cell;
    }else{
        MyMoneyBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyMoneyBottomCell"];
        cell.model = self.listDataArray[indexPath.row];
        return cell;
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setShadowImage:nil];
    CGFloat offset = self.tableView.contentOffset.y;
    [self.navigationController.navigationBar
     setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:255/255.0 green:201/255.0 blue:31/255.0 alpha:(offset / 64)>0.99?0.99:(offset / 64)]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar
     setShadowImage:[UIImage new]];
//    if (scrollView.contentOffset.y > 64) {
//        NSLog(@"偏移量大于64了");
//        [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
//        [self.navigationController.navigationBar setShadowImage:nil];
//    }
//    if (scrollView.contentOffset.y < 64) {
//
//        [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; //去除 navigationBar 底部的细线
//        self.navigationController.navigationBar.shadowImage = [UIImage new];
//    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 420.f;
    }
    return 70.f;
}
-(void)goSign{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/gradeApp/sign";
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:sessionId,@"sessionId", nil];
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsondic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        if ([jsondic[@"msg"] isEqual:@"操作成功"]) {
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"签到成功" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alertView show];
//        }
        [self.listDataArray removeAllObjects];
        [self getRecoredList];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

/**
 获取用户签到记录
 */
-(void)getRecoredList{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/gradeApp/integralRecordList";
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:sessionId,@"sessionId", nil];
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsonDic= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *listArra = jsonDic[@"list"];
        for (NSDictionary *dict in listArra) {
            RecordListModel *model = [RecordListModel modelWithDictionary:dict];
            [self.listDataArray addObject:model];
        }
        NSLog(@"%@",listArra);
        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
-(NSMutableArray *)listDataArray{
    if (_listDataArray == nil) {
        _listDataArray = [[NSMutableArray alloc] init];
    }
    return _listDataArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
